package com.ny.zmb.openapi.demo;

import com.alibaba.fastjson.JSONObject;
import com.ny.zmb.openapi.util.RSA256Util;
import com.ny.zmb.openapi.util.SignUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

/**
 * @author yangx
 * @description TODO
 * @date 2021/10/9
 */
public class AnsyNotifyDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(AnsyNotifyDemo.class);

    @RequestMapping(value="notify/demo",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public String notifyDemo(@RequestBody Map<String,String> param) throws Exception {
        /*1、打印异步通知参数*/
        LOGGER.info("异步通知接收的参数为:{}",JSONObject.toJSONString(param));
        if(param == null){
            //失败返回fail 字符串
            return "fail";
        }

        /*3、调用异步通知验签方法*/
        byte[] srcData = SignUtil.getSignDataStr1(param).getBytes("UTF-8");
        //银盛端的公钥证书
        String publicFilePath = "D:/datas/SHA-test/service.cer";
        boolean validateSignResult= RSA256Util.validateSign(publicFilePath, Base64.decodeBase64(param.get("sign")),srcData);
        if(!validateSignResult){
            System.out.println("验签失败，请确定提供的异步通知地址是否在银盛配置了RSA验签方式，如未配置，返回的sign值默认为国密加签");
            return "fail";
        }

        /*4、获取业务参数,具体业务参数详见文档，实现自己的逻辑代码*/
        String bizContent = param.get("bizContent");
        LOGGER.info("业务参数为:{}",bizContent);

        /*5、返回，成功返回success字符串*/
        return "success";
    }

}
